package com.mazewithtraps.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.bluetooth.*;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

import  bluetoothPackage.bluetoothEngine;

/**
 * Created by Роман on 06.05.14.
 */
public class ConnectionActivity extends Activity
{
    private int size;
    private BluetoothAdapter bluetooth;
    private ArrayAdapter<BluetoothDevice> mAdapter;
    ArrayAdapter<String> adapt;
    private static final int REQUEST_ENABLE_BT = 1;
    private Toast toast;
    private BluetoothSocket socket;
    private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c667");

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        size = getIntent().getExtras().getInt("size");
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_connection);
        bluetooth = BluetoothAdapter.getDefaultAdapter();
        if(bluetooth != null)
        {
            if (!bluetooth.isEnabled())
            {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                if (enableBtIntent.getFlags() == RESULT_CANCELED)
                {
                    toast = Toast.makeText(getApplicationContext(),
                            "Please turn on the Bluetooth adapter!",
                            Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.BOTTOM, 0, 0);
                    toast.show();
                }
            }

            mAdapter = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1);
            adapt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        }
        else
        {
            toast = Toast.makeText(getApplicationContext(),
                    "This device has no Bluetooth adapter",
                    Toast.LENGTH_LONG);
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toast.show();
        }
    }

    public void searchButton_Click(View v)
    {
//        Intent intent = new Intent(ConnectionActivity.this, PlayActivity.class);
//        intent.putExtra("size", size);
//        startActivity(intent);
        if (!bluetooth.isEnabled())
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            if (enableBtIntent.getFlags() == RESULT_CANCELED)
            {
                toast = Toast.makeText(getApplicationContext(),
                        "Please turn on the Bluetooth adapter!",
                        Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.BOTTOM, 0, 0);
                toast.show();
            }
        }
        else
        {
            showDialog(0);
        }
    }

    public void showMeButton_Click(View v)
    {
        if (!bluetooth.isEnabled())
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            if (enableBtIntent.getFlags() == RESULT_CANCELED)
            {
                toast = Toast.makeText(getApplicationContext(),
                        "Please turn on the Bluetooth adapter!",
                        Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.BOTTOM, 0, 0);
                toast.show();
            }
        }
        else
        {
            bluetoothEngine btEngine = new bluetoothEngine(bluetooth);
            BluetoothSocket servSocket = null;
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
            servSocket =  btEngine.asServer();
            if(servSocket != null)
            {
                Intent intent = new Intent(ConnectionActivity.this, PlayActivity.class);
                intent.putExtra("size", size);
                intent.putExtra("socket", (Parcelable) btEngine);
                intent.putExtra("type", "client");
                startActivity(intent);
            }
        }
    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        adapt.clear();
        mAdapter.clear();
        Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
        if (pairedDevices.size() > 0)
            for (BluetoothDevice device : pairedDevices)
            {
                adapt.add(device.getName() + "\n" + device.getAddress());
                mAdapter.add(device);
            }

        this.find();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("List of devices")
                .setAdapter(adapt,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                bluetoothEngine btEngine = new bluetoothEngine(bluetooth);
                                BluetoothSocket clSocket = null;
                                clSocket =  btEngine.asClient(mAdapter.getItem(id));
                                if(clSocket != null)
                                {
                                    Intent intent = new Intent(ConnectionActivity.this, PlayActivity.class);
                                    intent.putExtra("size", size);
                                    intent.putExtra("socket", (Parcelable) btEngine);
                                    intent.putExtra("type", "client");
                                    startActivity(intent);
                                }
                            }
                        });
        builder.setCancelable(true);
        return builder.create();
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                adapt.add(device.getName() + "\n" + device.getAddress());
                mAdapter.add(device);
                adapt.notifyDataSetChanged();
                mAdapter.notifyDataSetChanged();
            }
        }
    };

    public void find() {
        if (bluetooth.isDiscovering()) {
            // the button is pressed when it discovers, so cancel the discovery
            bluetooth.cancelDiscovery();
        }
        else {
            bluetooth.startDiscovery();

            registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        }
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }
//---------------------------------------------------------------------------------------------

}
